<?php

namespace Biz\Resources\User;

use Biz\Resources\TokenResource;
use Lumen\Core\Standards\stdToken;
use Lumen\Http\Resources\Json\Resource;

/**
 * UserResource.
 *
 * @license [http://www.85do.com] [杭州永奥网络科技有限公司]
 * @copyright Copyright (c) 2018-2026 Hangzhou Yongao Technology Co., Ltd. All rights reserved.
 */
class UserResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return array
     */
    public function toArray($request)
    {
        return [
            'uid'        => $this->uid,
            'avatar'     => $this->avatar,
            'nickname'   => $this->nickname,
            'created_at' => $this->created_at->getTimestamp(),
            $this->mergeWhen(! is_null($this->getPersonalAccessToken()), [
                'token' => $this->getPersonalAccessTokenResource(),
            ]),
            $this->mergeWhen(! is_null($this->getClient()), [
                'client' => $this->getUserClientResource(),
            ]),
            $this->mergeWhen(! is_null($this->getMember()), [
                'member' => $this->getUserMemberResource(),
            ]),
            $this->mergeWhen($this->relationLoaded('member'), [
                'member' => $this->getUserMemberResource(),
            ]),
        ];
    }

    /**
     * 获取Token响应资源.
     *
     * @return AppTokenResource|null
     */
    public function getPersonalAccessTokenResource()
    {
        if (! is_null($this->getPersonalAccessToken())) {
            $token    = (string) $this->getPersonalAccessToken();
            $stdToken = new stdToken();
            $stdToken->setAccessToken($token);

            return new TokenResource($stdToken);
        }

        return null;
    }

    /**
     * 获取客户响应资源.
     *
     * @return UserClientResource|null
     */
    public function getUserClientResource()
    {
        if ($this->isClient()) {
            if (! is_null($this->getClient())) {
                return new UserClientResource($this->getClient());
            }
        }

        return null;
    }

    /**
     * 获取成员响应资源.
     *
     * @return UserClientResource|null
     */
    public function getUserMemberResource()
    {
        if ($this->isMember()) {
            if (! is_null($this->getMember())) {
                return new UserMemberResource($this->getMember());
            }
            if ($this->relationLoaded('member')) {
                return new UserMemberResource($this->member);
            }
        }

        return null;
    }
}
